<?php
namespace app\api\controller;


use app\extra\ApiToken;
use app\extra\Response;
use EasyWeChat\Factory;
use think\Controller;
use think\Url;

/**
 * @title 微信授权登陆
 * @description 接口说明
 * @group 微信报名分销
 */
class WeChat extends Controller
{
    protected $config;
    static public $_login_key;
    use Response;
    public function __construct()
    {
        self::$_login_key = Base::$_login_key;
        parent::__construct();
        $this->config = [
            'app_id' => ENV("WX_APP_ID"),
            'secret' => ENV("WX_APP_SECRET")
        ];
    }
    private function _weChatHandle($user){
        $model = model('WeChat');
        $userData = $model->where('openid', $user['id'])->find();
        if (empty($userData)){
            $data = [
                'openid' => $user['id'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar']
            ];
            $r = $model->createAdd($data);
            if ($r === false){
                $this->responseFail($model->getError());
            }
            $userData = $r;
        } else {
            $save = [
                'id' => $userData['id']
            ];
            $flag = false;
            if ($userData['nickname'] != $user['nickname']) {
                $flag = true;
                $save['nickname'] = $user['nickname'];
            }
            if ($userData['avatar'] != $user['avatar']) {
                $flag = true;
                $save['avatar'] = $user['avatar'];
            }
            if ($flag){
                if ($model->updateSave($save) === false){
                    $this->responseFail($model->getError());
                }
            }
        }
        sysLogs('微信授权登陆:'.$userData['nickname'].';openid:'.$userData['openid'], json_encode($userData));
        ApiToken::$send_flg = true;
        $this->setUser($userData);
    }
    public function callback(){
        $app = Factory::officialAccount($this->config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $data = $user->getAttributes();
        $this->_weChatHandle($data);
        $redirect = input('get.redirect');
        $redirect = base64_decode($redirect);
        header('Location: ' . $redirect);
    }
    /**
     * @title 微信授予权登陆
     * @description 授权并创建登陆信息
     * @author hardy
     * @url /api/WeChat/auth
     * @method get
     *
     * @param name:redirect type:string require:1 default: other: desc:授权登陆成功后跳转的地址，该链接必须通过base64编码后的值，并且是带有http或https开头
     */
    public function auth(){
        ApiToken::$send_flg = true;
        $redirect = input("get.redirect");
        if (empty($redirect)){
            $this->responseFail('缺少参数redirect，该参数是base64加密后的值');
        }
        setcookie(\app\extra\behavior\AuthBehavior::$authKey, ApiToken::$sid, $expire = 0, '/');
        $app = Factory::officialAccount($this->config);
        $response = $app->oauth->scopes(['snsapi_userinfo'])->redirect(fullPath('callback', ['redirect' => $redirect, 'token_id' => ApiToken::$sid]));
        $response->send();
    }
    /**
     * @title 获取登陆信息
     * @description 获取登陆信息
     * @author hardy
     * @url /api/WeChat/info
     * @method get
     *
     */
    public function info(){
        $data = getPersonInfo();
        if (empty($data)){
            setcookie(\app\extra\behavior\AuthBehavior::$authKey, ApiToken::$sid, $expire = 0, '/');
            $this->response('未登录', false, '', 401, fullPath('auth'));
        }
        $this->responseSuccess($data);
    }
    /**
     * @title 模拟登陆（开发使用）
     * @description 获取登陆信息
     * @author hardy
     * @url /api/WeChat/testLogin
     * @method get
     *
     * @param name:id type:int require:0 default: other: desc:用户id
     */
    public function testLogin(){
        $id = input("get.id", 1);
        if (empty($id)){
            $this->responseFail('id必填');
        }
        setcookie(\app\extra\behavior\AuthBehavior::$authKey, ApiToken::$sid, $expire = 0, '/');
        $userData = model('WeChat')->where('id', $id)->find();
        if (empty($userData)){
            $this->responseFail('该用户不存在id='.$id);
        }
        ApiToken::$send_flg = true;
        $this->setUser($userData);
        $this->responseSuccess($userData);
    }
}